package com.m.IO;

import java.io.*;

/**
 * 关闭过滤流会自动关闭所包装的流
 * 使用过滤流中间进行flush()
 * finally中可能还会存在异常需要再次进行try-catch处理异常
 *
 *
 * @author Mc.Chai
 * @program: Java基础
 * @create 2021-11-23-20:19 20:19
 */
public class TestTryCatchFinallyForStream {
    public static void main(String[] args) {
        OutputStream outputStream=null;
        BufferedOutputStream bufferedOutputStream=null;
        InputStream inputStream=null;
        try {
            outputStream=new FileOutputStream("try.txt");
            bufferedOutputStream=new BufferedOutputStream(outputStream);
            bufferedOutputStream.write('A');
            bufferedOutputStream.flush();
            inputStream=new FileInputStream("try.txt");
            byte[] cache=new byte[4];
            while (true){
                int n=inputStream.read(cache);
                if (n==-1) break;
                for (int i = 0; i < n; i++) {
                    System.out.println((char)cache[i]);

                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
                try {
                    //防止空指针异常的发生，如果上面发生异常inputStream赋值失败，会发生空指针异常
                    //再关闭输入流后关闭输出流
                    if (inputStream!=null){
                        inputStream.close();
                    }
                    if (outputStream!=null) {
                        bufferedOutputStream.close();      //将最外层的输出流的关闭
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

        }
    }
}
